﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework;
using ElementumForever.Enums;

namespace ElementumForever
{
    public class InputControl
    {
        KeyboardState previousKeyboardState, currentKeyboardState;// Keyboard state variables
        MouseState previousMouseState;

        public delegate bool HandleKeyInput(Keys keyId, EButtonState state);
        public event HandleKeyInput handleKeyInputEvent;
        public delegate bool HandleMouseInput(MouseState state);
        public event HandleMouseInput handleMouseClickInputEvent;
        public event HandleMouseInput handleMouseDragInputEvent;

        public InputControl()
        {
            currentKeyboardState = new KeyboardState();
            previousMouseState = Mouse.GetState();
        }

        public void OnUpdate(GameTime gameTime)
        {
            previousKeyboardState = currentKeyboardState;
            currentKeyboardState = Keyboard.GetState();

            Keys[] oldPressKeys = previousKeyboardState.GetPressedKeys();
            Keys[] currentPressKeys = currentKeyboardState.GetPressedKeys();

            foreach (Keys key in oldPressKeys)
            {
                if (currentKeyboardState.IsKeyDown(key))
                    OnHandleKeyInput(key, EButtonState.down);
                else
                    OnHandleKeyInput(key, EButtonState.up);
            }

            if (previousMouseState.LeftButton == ButtonState.Released && Mouse.GetState().LeftButton == ButtonState.Pressed)
                OnHandleMouseClickInput(Mouse.GetState());

            if (previousMouseState.LeftButton == ButtonState.Pressed && Mouse.GetState().LeftButton == ButtonState.Pressed)
                OnHandleMouseDragInput(Mouse.GetState());

            previousMouseState = Mouse.GetState();
        }

        private bool OnHandleKeyInput(Keys keyId, EButtonState state)
        {
            if (handleKeyInputEvent != null)
                handleKeyInputEvent(keyId, state);
            return false;
        }

        private bool OnHandleMouseClickInput(MouseState state)
        {
            if (handleMouseClickInputEvent != null)
                handleMouseClickInputEvent(state);
            return false;
        }
        private bool OnHandleMouseDragInput(MouseState state)
        {
            if (handleMouseDragInputEvent != null)
                handleMouseDragInputEvent(state);
            return false;
        }

    }
}
